const mysql = require('mysql2/promise');
require('dotenv').config();

// 数据库连接配置
const dbConfig = {
  host: process.env.DB_HOST || 'localhost',
  port: process.env.DB_PORT || 3306,
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'game_appointment',
  charset: 'utf8mb4',
  timezone: '+08:00',
  acquireTimeout: 60000,
  timeout: 60000,
  reconnect: true
};

// 创建连接池
const pool = mysql.createPool({
  ...dbConfig,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
  acquireTimeout: 60000,
  timeout: 60000
});

// 测试数据库连接
async function testConnection() {
  try {
    const connection = await pool.getConnection();
    console.log('✅ 数据库连接成功');
    connection.release();
    return true;
  } catch (error) {
    console.error('❌ 数据库连接失败:', error.message);
    return false;
  }
}

// 执行查询的辅助函数
async function query(sql, params = []) {
  try {
    const [rows] = await pool.execute(sql, params);
    return rows;
  } catch (error) {
    console.error('数据库查询错误:', error);
    throw error;
  }
}

// 执行事务的辅助函数
async function transaction(callback) {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    const result = await callback(connection);
    await connection.commit();
    return result;
  } catch (error) {
    await connection.rollback();
    throw error;
  } finally {
    connection.release();
  }
}

// 格式化查询结果
function formatRows(rows) {
  if (!rows || rows.length === 0) return [];
  
  return rows.map(row => {
    const formatted = {};
    for (const [key, value] of Object.entries(row)) {
      // 处理时间字段
      if (value instanceof Date) {
        formatted[key] = value.toISOString();
      } else if (key.includes('_at') && typeof value === 'string') {
        formatted[key] = new Date(value).toISOString();
      } else {
        formatted[key] = value;
      }
    }
    return formatted;
  });
}

// 构建WHERE条件的辅助函数
function buildWhereClause(conditions = {}) {
  const clauses = [];
  const params = [];
  
  for (const [key, value] of Object.entries(conditions)) {
    if (value !== undefined && value !== null && value !== '') {
      if (Array.isArray(value)) {
        clauses.push(`${key} IN (${value.map(() => '?').join(', ')})`);
        params.push(...value);
      } else if (typeof value === 'object' && value.operator) {
        clauses.push(`${key} ${value.operator} ?`);
        params.push(value.value);
      } else {
        clauses.push(`${key} = ?`);
        params.push(value);
      }
    }
  }
  
  return {
    clause: clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '',
    params
  };
}

// 构建分页的辅助函数
function buildPagination(page = 1, limit = 10) {
  const offset = (page - 1) * limit;
  return {
    clause: `LIMIT ${limit} OFFSET ${offset}`,
    offset,
    limit
  };
}

module.exports = {
  pool,
  query,
  transaction,
  testConnection,
  formatRows,
  buildWhereClause,
  buildPagination
};
